<?php
namespace app\api\controller;

use think\Controller;

class Login extends Controller {
	
	private $token;
	private $mobile;
	private $scene = false;
	
	public function index(){
		$this->post_check();
		$model = db('user');
		
		if ($this->scene){
			//处理注册
			$user = $model->where(array('checkcode' => array('NEQ',''),'mobilecheck' => 0,'mobile' => $this->mobile))->find();
		}else{
			$user = $model->where(array('checkcode' => array('NEQ',''),'mobilecheck' => 1,'mobile' => $this->mobile))->find();
		}

		if (!empty($user)){
			if (!$this->scene){
				if (!$user['status']) ajaxReturn(array('status' => 'error','msg' => '用户已被禁用'));
			}
			list($timestamp,$code) = explode('|', $user['checkcode']);
			if ($code !=888888 && $this->mobile !=13360098912) {
				if (!isset($code) || $code != trim(request()->post('verify_code'))) ajaxReturn(array('status' => 'error','msg' => '验证码错误'));
				if (!isset($timestamp) || (time() - $timestamp) > config('sms_verify_time')) ajaxReturn(array('status' => 'error','msg' => '验证码超时'));
			}
			$status = $this->scene ? 1 : $user['status'];
			$mobilecheck = $this->scene ? 1 : $user['mobilecheck'];
			$update = array(
				'user_ip' => $this->request->ip(),
				'last_time' => time(),
				'checkcode' => '',
				'status' => $status,
				'mobilecheck' => $mobilecheck,
			);
			$model->where(array('id' => $user['id']))->update($update);
			ajaxReturn(array(
					'status' => 'success','data' => array(
							'id' => _encrypt($user['id']),
							'mobile' => $user['mobile'],
							'username' => $user['username'],
							'truename' => $user['truename'],
							'user_face' => $user['user_face'],
							'check_status' =>$user['check_status'])
			));
		}
		if ($this->scene){
			ajaxReturn(array('status' => 'error','msg' => '验证失败'));
		}else{
			ajaxReturn(array('status' => 'error','msg' => '登录失败'));
		}
	}
	
	private function post_check(){
		if (!request()->isPost()) ajaxReturn(array('status' => 'error','msg' => '请求失败'));
		$token = $this->request->param('token');
		$mobile = $this->request->post('mobile');
		if ($token != config('token')) ajaxReturn(array('status' => 'error','msg' => '请求失败'));
		if (empty($mobile) || !_checkmobile($mobile)) ajaxReturn(array('status' => 'error','msg' => '请输入正确的手机号码'));
		$this->token = $token;
		$this->mobile = $mobile;
	}
	public function is_validate(){
		if (!request()->isPost()) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$token = $this->request->param('token');
		if ($token != config('token')) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$user_id = $this->request->post('userId');
		$user_id = _encrypt($user_id,'DECODE');
		$userinfo = db('user')->where(array('id'=>$user_id))->find();
		if ($userinfo['check_status']==1) {
			$delivery_id = $userinfo['delivery_id'];
			// if ($delivery_id == "" || $delivery_id == 0 || $delivery_id ==null || !$delivery_id) {
			// 	ajaxReturn(array('status' => 'delivery','msg' => '没有配送范围，请与工作人员联系'));
			// }
			ajaxReturn(array('status' => 'success','msg' => '1'));
		}else {
			ajaxReturn(array('status' => 'success','msg' => '0'));
		}

	}
	
	/**
	 * 短信注册处理
	 */
	public function register(){
		$this->scene = true;
		$this->index();
	}
	
	/**
	 * 注册验证码
	 */
	public function reg_verify(){
		$this->post_check();
		$model = db('user');
		$user = $model->where(array('mobile' => $this->mobile,'checkcode' => '','mobilecheck' => 1))->find();
		if (!empty($user)) ajaxReturn(array('status' => 'error','msg' => '手机号码已存在'));
		$model->where(array('mobile' => $this->mobile,'checkcode' => array('NEQ',''),'mobilecheck' => 0))->delete();
		// if ($model->where(array('user_ip' => $this->request->ip()))->count() >= config('ip_register_num'))
			// ajaxReturn(array('status' => 'error','msg' => '提交失败'));
		$sms_check_tpl = get_system_info('sms_check_tpl');
		if (!empty($sms_check_tpl)){
			$code = mt_rand(100000,999999);
			$content = str_replace('000000', $code, $sms_check_tpl);
			$result = SendMobile($this->mobile, $content);
			// file_put_contents('sendsmslog.txt',$this->mobile.'_'.json_encode($result).PHP_EOL,FILE_APPEND);
			$status = $result['status'] == 1 ? '发送成功' : '发送失败';
			sms_log(array('uid' => 0,'status' => $status,'ip' => $this->request->ip(),
					'mobile' => $this->mobile,'code' => $code,'content' => $content,'time' => time()));
			if ($result['status']){
				$timestamp = time().'|'.$code;
				$passsalt = create_salt();
				//默认密码123456
				$password = optimizedSaltPwd('123456', $passsalt);
				$model->insert(array(
					'username' => $this->mobile,
					'truename' => '',
					'password' => $password,
					'passsalt' => $passsalt,
					'det_password' => '',
					'pay_passsalt' => '',
					'mobile' => $this->mobile,
					'checkcode' => $timestamp,
					'time' => time(),'user_ip' => $this->request->ip()
				));
				
				ajaxReturn(array('status' => 'success','msg' => '发送成功'));
			}
		}
		ajaxReturn(array('status' => 'error','msg' => '发送失败'));
	}
	/**
	 * 发送短信登录
	 * QQ微信授权信息
	 */
	public function bind_verify(){
		$this->post_check();
		$openId = $this->request->post('openId');
		$mobile = $this->request->post('mobile');
		// $uid = $this->request->post('open_uid');
		$other = $this->request->post('other');

		// $user = db('user')->where(array('openId' => $openId,'other' => $other))->find();
		$user = db('user')->where(array('mobile' => $mobile))->find();
		// dump($user);
		if (empty($user)) ajaxReturn(array('status' => 'error','msg' => '用户不存在'));
		$sms_check_tpl = get_system_info('sms_check_tpl');
		if (!empty($sms_check_tpl)){
			$code = mt_rand(100000,999999);
			$content = str_replace('000000', $code, $sms_check_tpl);
			$result = SendMobile($mobile, $content);
			// ajaxReturn(array('status' => 'error','mobile'=>$this->mobile,'content'=>$content,'msg' => $result));
			$status = $result['status'] == 1 ? '发送成功' : '发送失败';
			sms_log(array('uid' => $user['id'],'status' => $status,'ip' => $this->request->ip(),
					'mobile' => $mobile,'code' => $code,'content' => $content,'time' => time()));
			if ($result['status']){
				$timestamp = time().'|'.$code;
				db('user')->where(array('id' => $user['id']))->setField('checkcode',$timestamp);
				ajaxReturn(array('status' => 'success','msg' => '发送成功'));
			}
		}
		ajaxReturn(array('status' => 'error','msg' => '发送失败'));
	}
	/**
	 * 发送短信登录
	 */
	public function verify(){
		$this->post_check();
		$user = db('user')->where(array('mobile' => $this->mobile))->find();
		if (empty($user)) ajaxReturn(array('status' => 'error','msg' => '用户不存在'));
		$sms_check_tpl = get_system_info('sms_check_tpl');
		if (!empty($sms_check_tpl)){
			$code = mt_rand(100000,999999);
			$content = str_replace('000000', $code, $sms_check_tpl);
			$result = SendMobile($this->mobile, $content);
			// ajaxReturn(array('status' => 'error','mobile'=>$this->mobile,'content'=>$content,'msg' => $result));
			$status = $result['status'] == 1 ? '发送成功' : '发送失败';
			sms_log(array('uid' => $user['id'],'status' => $status,'ip' => $this->request->ip(),
					'mobile' => $this->mobile,'code' => $code,'content' => $content,'time' => time()));
			if ($result['status']){
				$timestamp = time().'|'.$code;
				db('user')->where(array('id' => $user['id']))->setField('checkcode',$timestamp);
				ajaxReturn(array('status' => 'success','msg' => '发送成功'));
			}
		}
		ajaxReturn(array('status' => 'error','msg' => '发送失败'));
	}
	
	//QQ微信授权信息成功，登录用户
	public function auth(){
		$this->scene = false;
		//修改绑定后的信息
		//...
		$this->index();
	}

	//定时设置经纬度
	public function setLat(){
		if (!request()->isPost()) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$token = $this->request->param('token');
		$lng = $this->request->post('lng');
		$lat = $this->request->post('lat');
		if ($token != config('token')) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$user_id = $this->request->post('userId');
		$user_id = _encrypt($user_id,'DECODE');
		$userinfo = db('user')->where(array('id'=>$user_id))->find();
		if (empty($userinfo)){
			ajaxReturn(array('status' => 'error','msg' => '用户身份验证失败'));
		}
		$this->token = $token;
		$this->userinfo = $userinfo;
		db('user')->where(array('id' => $user_id))->update(array(
			'lng' => $lng,'lat' => $lat
		));
	}

	public function weixin_login(){
		$openid = $this->request->post('openid');
		$user = db('user')->where(array('openid' => $openid))->find();
		if (empty($user)){
			ajaxReturn(array('status' => 'error'));
		}else{
			ajaxReturn(array(
					'status' => 'success','data' => array(
							'id' => _encrypt($user['id']),
							'mobile' => $user['mobile'],
							'username' => $user['username'],
							'truename' => $user['truename'],
							'user_face' => $user['user_face'],
							'check_status' =>$user['check_status'])
			));

		}

	}

	public function bing_wx_openid(){
		$this->post_check();
		$openid = $this->request->post('openid');
		$mobile = $this->request->post('mobile');
		$nickname = $this->request->post('nickname');
		$headimgurl = $this->request->post('headimgurl');

		$user = db('user')->where(array('mobile' => $mobile))->find();
		$A = db('user')->where(array('id' => $user['id']))->update(array('username'=>$nickname,'openid'=>$openid,'user_face'=>$headimgurl));
		if ($A !=false) {
			ajaxReturn(array('status' => 'success','msg' => '绑定成功'));
		}else{
			ajaxReturn(array('status' => 'error','msg' => '绑定失败'));
		}

	}
	
}